/**
 * @author lulongwen
 * Date: 2023-03-08 21:57
 * Description:
 */

import { useCallback } from 'react';
import ReactFlow, {
  Controls,
  Background,
  addEdge,
  Connection,
  Edge,
  EdgeTypes,
  Node,
  useEdgesState,
  useNodesState,
} from 'reactflow';

import CustomEdge from './CustomEdge';
import CustomEdgeStartEnd from './CustomEdgeStartEnd';

const initialNodes: Node[] = [
  {
    id: '1',
    type: 'input',
    data: { label: 'Node 1' },
    position: { x: 0, y: 0 },
  },
  {
    id: '2',
    data: { label: 'Node 2' },
    position: { x: 0, y: 200 }
  },
  {
    id: '3',
    data: { label: 'Node 3' },
    position: { x: 200, y: 0 }
  },
  {
    id: '4',
    data: { label: 'Node 4' },
    position: { x: 200, y: 200 }
  },
];

const initialEdges: Edge[] = [
  {
    id: 'e1-2',
    source: '1',
    target: '2',
    data: {
      label: 'edge label',
    },
    type: 'CustomEdge',
  },
  {
    id: 'e3-4',
    source: '3',
    target: '4',
    data: {
      startLabel: '开始 edge label',
      endLabel: '结束 edge label',
    },
    type: 'CustomEdgeStartEnd',
  },
];

const edgeTypes: EdgeTypes = {
  CustomEdge,
  CustomEdgeStartEnd,
};

const EdgesFlow = (props: any) => {
  const { thumbnail } = props;

  const [nodes, , onNodesChange] = useNodesState(initialNodes);
  const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
  const onConnect = useCallback(
    (params: Connection | Edge) => setEdges((eds) => addEdge(params, eds)),
    [setEdges]
  );

  return (
    <ReactFlow
      nodes={nodes}
      edges={edges}
      onNodesChange={onNodesChange}
      onEdgesChange={onEdgesChange}
      onConnect={onConnect}
      edgeTypes={edgeTypes}
      fitView={thumbnail}
    >
      {!thumbnail && <Controls /> }
      <Background />
    </ReactFlow>
  );
};

export default EdgesFlow;
